<template>
  <div>
    <!--顶部标题 -->
    <div>
      <x-header
        :left-options="{ backText: '', showBack: false }"
        @on-click-more="showMenusOfPersonalInfo = true"
        >{{ locationTitle }}</x-header
      >
    </div>
    <div style="height: 10px; background-color: rgb(237, 237, 237)" />
    <!-- 柱形统计表 -->
    <div>
      <canvas id="myChart" style="width: 100%"></canvas>
    </div>
    <!-- 文字统计 -->
    <div class="textStatistic">
      <div class="text">
        <span>总时长 {{ test.sumTime }}h</span>
        <!-- <span>
          较上周
          <span class="contrast">
            {{ weekStatistic.compareTime }}
            <i
              v-if="weekStatistic.compareTime > 0"
              class="fa fa-arrow-up"
              aria-hidden="true"
            ></i>
            <i v-else class="fa fa-arrow-down" aria-hidden="true"></i>
          </span>
        </span> -->
      </div>
      <div class="text otherText" v-for="item in test.tagRank" :key="item">
        <span>{{ item.dataName }}</span>
        <span
          >{{ item.dataContent }}h&nbsp;&nbsp;&nbsp;{{
            getRatio(item).toFixed(2)
          }}%</span
        >
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from "Vuex";
import { XHeader } from "vux";
import F2 from "@antv/f2/lib/index-all";
import statisitical from "api/statisitical";
import util from "utilMethods/time";
export default {
  name: "addReport",
  data() {
    return {
      locationTitle: "统计情况", //顶部标题栏显示的文字
      weekStatistic: {}, //页面的显示数据
      chartData: [], //图表的数据
      timeSpan: [],
      test: {},
    };
  },
  components: {
    XHeader,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  mounted() {
    this.getData();
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    async getData() {
      // const result = await statisitical.getWeekStatistic(this.userInfo.userId);
      const result = await statisitical.getStatis({
        end: util.getCurrentDay(),
        start: "2020-09-21", //一个获得开始时间的函数
        userId: +this.userInfo.userId,
      });
      if (result.code === 1) {
        this.weekStatistic = result.data;
        let statisticalData = this.weekStatistic.statisticalData;
        for (let key in statisticalData) {
          let temp = {
            date: key,
            steps: statisticalData[key],
          };
          // 给周一加上first属性
          if (new Date(key).getDay() == 1) {
            temp.first = true;
          }
          this.chartData.push(temp);
        }
      }
      this.init();
    },
    getRatio(item) {
      let result = item.dataContent / this.test.sumTime;
      return result.toFixed(2) * 100;
    },
    formatNumber(n) {
      return String(Math.floor(n * 100) / 100).replace(
        /\B(?=(\d{3})+(?!\d))/g,
        ","
      );
    },
    init() {
      const originDates = [];
      const originSteps = [];
      const firstDayArr = [];
      const that = this;
      that.timeSpan = [];
      let count = 0,
        length = this.chartData.length;
      this.chartData.forEach(function (obj) {
        if (count++ >= length - 7) {
          // 这个是控制一次显示多少数据的！！
          originDates.push(obj.date); //日期
          originSteps.push(obj.steps); //时长
        }
        if (obj.first) {
          firstDayArr.push(obj); //是否周一
        }
      });
      const chart = new F2.Chart({
        id: "myChart",
        pixelRatio: window.devicePixelRatio,
      });
      chart.source(this.chartData, {
        date: {
          type: "timeCat",
          tickCount: 4,
          values: originDates,
          // mask: "MM-DD",
        },
        steps: {
          tickCount: 5,
        },
      });
      chart.axis("date", {
        tickLine: {
          length: 4,
          stroke: "#cacaca",
        },
        label: function label(text) {
          that.timeSpan.push(text)
          return {
            text: text,
            fill: "#cacaca",
          };
        },
        line: {
          top: true,
        },
      });

      chart.axis("steps", {
        position: "right",
        label: function label(text) {
          return {
            text: that.formatNumber(text * 1),
            fill: "#cacaca",
          };
        },
        grid: {
          stroke: "#d1d1d1",
        },
      });
      chart.tooltip({
        showItemMarker: false,
        background: {
          radius: 2,
          padding: [3, 5],
        },
        onShow: function onShow(ev) {
          const items = ev.items;
          items[0].name = "";
          items[0].value = (+items[0].value).toFixed(2) + " 小时";
        },
      });
      chart
        .interval()
        .position("date*steps")
        .style({
          radius: [2, 2, 0, 0],
        });

      firstDayArr.forEach(function (obj) {
        chart.guide().line({
          top: false,
          start: [obj.date, "min"],
          end: [obj.date, "max"],
          style: {
            lineWidth: 1,
            stroke: "#A4A4A4",
          },
        });
        chart.guide().text({
          position: [obj.date, "max"],
          content: obj.date.substring(5),
          style: {
            textAlign: "start",
            fill: "#cacaca",
            textBaseline: "top",
          },
          offsetX: 5,
          offsetY: 5,
        });
      });

      // 定义进度条
      chart.scrollBar({
        mode: "x",
        xStyle: {
          backgroundColor: "#e8e8e8",
          fillerColor: "#808080",
          offsetY: -2,
        },
      });
      chart.interaction("pan", {
        onEnd(ev) {
          // 这里是每次滑动过后获取timeSpan
          that.timeSpan=[]
          const xScale = chart.getXScale().values
          const range = chart.get('_limitRange').date
          for(let index=0;index<range.length;++index){
            if(range[index] === xScale[0]){
              that.timeSpan.push(that.chartData[index].date)
              that.timeSpan.push(that.chartData[index+6].date)
              break
            }
          }
          that.getInfo();
        },
      });
      chart.render();
      // 这里是第一次进入没有移动的时候，需要对timeSpan进行处理后调用getInfo
      that.timeSpan[1] = that.timeSpan[that.timeSpan.length-1]
      that.timeSpan.length=2
      this.getInfo();
    },
    async getInfo() {
      const result = await statisitical.getStatis({
        end: this.timeSpan[1],
        start: this.timeSpan[0], //一个获得开始时间的函数
        userId: +this.userInfo.userId,
      });
      if (result.code === 1) {
        this.test = result.data;
      }
    },
  },
};
</script>
<style lang="less">
.textStatistic {
  .text {
    display: flex;
    justify-content: space-between;
    margin: 10px;
    padding: 5px;
    span {
      font-size: 18px;
      font-weight: bold;
      .contrast {
        color: green;
        i {
          color: green;
        }
      }
    }
  }
  .otherText {
    span {
      font-size: 15px;
      font-weight: bold;
    }
  }
}
</style>